var appPath = getAppPath();
var EDIT_IMG_IDX = 0;

$(function(){

	// 合作方(检索用)
	$("#queryPartner").combobox({
		url:appPath+'/yjxOrders/getPartnerForCombo.action?blkFlg=1',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdM){
			// TODO
		}
	});
	
	// 合作方(更新用)
	$("#updPartner").combobox({
		url:appPath+'/yjxOrders/getPartnerForCombo.action',
		valueField:'id',
		textField:'name',
		onSelect:function(selRecdM){
			// TODO
		}
	});
	
	
	initOrdersGrid();
	
	// 初始化 视频播放 点击红叉  停止播放
	$('#playVideoDlg').window({
	       onBeforeClose:function(){ 
	    	   var myVideo = document.getElementsByTagName('video')[0];
	    	   myVideo.pause(); // 暂停播放
	       }
	});
});

function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    var h = dt.getHours();
    var mm = dt.getMinutes();
    var s = dt.getSeconds();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d)+' '+(h<10?('0'+h):h)+':'+(mm<10?('0'+mm):mm)+':'+(s<10?('0'+s):s);
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 初始化加载一键秀 订单列表 信息
function initOrdersGrid(){
	$('#ordersGrid').datagrid({
	    url:appPath + "/yjxOrders/getOrdersInfoPg.action",
	    height:'full',
	    nowrap: false,// 换行
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'order_id',title:'订单ID',width:25,align:'center',sortable:false},
  	        {field:'order_no',title:'订单号',width:53,align:'center',sortable:false},
  	        {field:'pay_order_no',title:'支付订单号',width:53,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red;">'+value+'</span>';
		    	  }
		      },
  	        {field:'odr_dtl_type_tag',title:'订单分类',width:53,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(value){
		    			  var show = '<span style="color:#A020F0;">其它</span>';
		    			  switch (value){
		    			  case 2: show = '<span style="color:#3B3B3B;">去水印</span>';break;
		    			  case 4: show = '<span style="color:#8B6914;">秒杀订单</span>';break;
		    			  case 8: show = '<span style="color:#8B6914;">VIP订单</span>';break;
		    			  case 16: show = '<span style="color:#8B6914;">充值订单</span>';break;
		    			  case 24: show = '<span style="color:#8B6914;">VIP+充值</span>';break;
		    			  case 32: show = '<span style="color:#8B6914;">待定订单</span>';break;
		    			  }
		    		  }
		    		  return show;
		    	  }
		    },
		    {field:'classify',title:'明细分类',width:53,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var t = rowData.odr_dtl_type_tag;
		    		var show = '<span style="color:#A020F0;">其它</span>';
		    		switch (t){
		    			case 2: 
		    				if(value){
			    				switch (value){
			    				case 1: show = '<span style="color:#3B3B3B;">[设计]去水印</span>';break;
			    				case 1020: show = '<span style="color:#8B6914;">[视频]去水印</span>';break;
			    				}
			    			}
		    				break;
		    			case 4: show = '<span style="color:#8B6914;">秒杀订单</span>';break;
		    			case 8: show = '<span style="color:#8B6914;">VIP</span>';break;
		    			case 16: show = '<span style="color:#8B6914;">充值</span>';break;
		    			case 24: show = '<span style="color:#C5C1AA;">VIP&充值</span>';break;
		    			case 32: show = '<span style="color:#8B6914;">待定订单</span>';break;
		    		}
		    		return show;
		    	}
		    },
		    {field:'downInfo',title:'导订单',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
  	        		return "<a href='javascript:void(0)' style='color:red' onClick='downOrderInfo("+rowData.order_id+")'>导出</a>";
	        	}
		    },
  	        {field:'user_id',title:'用户ID',width:43,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		var nickname = rowData.nickname;
		    		var thirdName = rowData.thirdName;
		    		var cl = '';
		    		if (rowData.user_delFlg == 1){
		    			cl = 'red';
		    		}
		    		if (value && nickname && nickname !== ''){
		    			return '<font color="'+cl+'">UID:'+value+'</font></br><span style="color:green;font-size:9px;">'+nickname+'</span>';
		    		} else if (thirdName && thirdName !== '') {
	    				return '<font color="'+cl+'">UID:'+value+'</font></br><span style="color:green;font-size:9px;">'+thirdName+'</span>';
	    			} else {
	    				return '<font color="'+cl+'">UID:'+value+'</font></br><span style="color:green;font-size:9px;">n/A</span>';
	    			}
		    	}
  	        },
  	        {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
	        {field:'detail_cnt',title:'订单明细',width:35,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return "N/A";
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.order_id+")'>查看</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
	        		var show = getState4Show(value);
	        		if(value==40||value==50) {
	        			return show;
	        		} else {
	        			return "<a href='javascript:void(0)' onClick='editState("+rowData.order_id+")'>"+show+"</a>";
	        		}
	        	}
		    },
		    {field:'downInfo2',title:'用户文档',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.order_id) return "N/A";
  	        		var t = rowData.odr_dtl_type_tag;//类型 只有去水印的导出用户文档
  	        		if(t&&(t&2)!=0){//则表明是去水印
  	        			return "<a href='javascript:void(0)' onClick='downOdrUserDocInfo("+rowData.order_id+")'>导出</a>";
  	        		}
  	        		return 'N/A';
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:25,align:'center',sortable:false},
  	        {field:'pay_platform',title:'支付平台',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pf = '<span style="color:red">其它</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: pf="微信"; break;
  	        			case 20: pf="支付宝"; break;
  	        			case 30: pf="苹果内购"; break;
  	        			case 100: pf="<font color='#7CCD7C'>示界港</font>"; break;
  	        		}
  	        		return pf;
	        	}
		    },
	        {field:'total_fee',title:'订单金额',width:37,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id) return "N/A";
		    		  var show = Number(value||'0')/100;
		    		  return '<span style="color:red;">'+show+'</span>元';
		    	  }
		      },
		    {field:'coupon_id',title:'券ID',width:30,align:'center',sortable:false},
		    {field:'coupon_fee',title:'优惠金额',width:35,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id || !rowData.coupon_id) return "";
		    		  var show = Number(value||'0')/100;
		    		  if(show>0) {
		    			  show = '<span style="color:green;">'+show+'</span>';
		    		  }
		    		  return show+'元';
		    	  }
		    },
	        {field:'create_time',title:'创建时间',width:50,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'重置时间',
				iconCls:'icon-reload',
				handler:function(){
					clearTime();
				}
			},
			{
				text:'批量导出订单',
				iconCls:'icon-save',
				handler:function(){
					exportAlls();
				}
			},
			{
				text:'导出用户文档',
				iconCls:'icon-save',
				handler:function(){
					exportOdrDocInfo();
				}
			}
			
		]
	});
}

/*
 *	 查看将要被导出的订单列表
 */
function initExOrderGrid(){
	var allOrderId='';
	$('#exOrderGrid').datagrid({
	    url:appPath + "/yjxOrders/getOrdersInfoPg.action?page=1&&rows=1000",
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    fit:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    AllowPaging :false,
	    columns:[[
  	        {field:'order_id',title:'订单ID',width:25,align:'center',sortable:false,
  	        	formatter:function(value, rowData,rowIndex){
  	        		allOrderId += value +",";
  	        		$("#allIds").val(allOrderId);
  	        		return value;
  	        	}
  	        },
  	        {field:'order_no',title:'订单号',width:50,align:'center',sortable:false},
  	        {field:'pay_order_no',title:'支付订单号',width:50,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  return '<span style="color:red;">'+value+'</span>';
		    	  }
		    },
		    {field:'classify',title:'明细分类',width:53,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var t = rowData.odr_dtl_type_tag;
		    		var show = '<span style="color:#A020F0;">其它</span>';
		    		switch (t){
		    			case 2: 
		    				if(value){
			    				switch (value){
			    				case 1: show = '<span style="color:#3B3B3B;">[设计]去水印</span>';break;
			    				case 1020: show = '<span style="color:#8B6914;">[视频]去水印</span>';break;
			    				}
			    			}
		    				break;
		    			case 4: show = '<span style="color:#8B6914;">秒杀订单</span>';break;
		    			case 8: show = '<span style="color:#8B6914;">VIP</span>';break;
		    			case 16: show = '<span style="color:#8B6914;">充值</span>';break;
		    			case 24: show = '<span style="color:#C5C1AA;">VIP&充值</span>';break;
		    			case 32: show = '<span style="color:#8B6914;">待定订单</span>';break;
		    		}
		    		return show;
		    	}
		    },
  	        {field:'user_id',title:'用户ID',width:30,align:'center',sortable:false},
  	        {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
	        {field:'detail_cnt',title:'订单明细',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return "N/A";
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.order_id+")'>查看</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:35,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
	        		var show = getState4Show(value);
	        		if(value==40||value==50) {
	        			return show;
	        		} else {
	        			return show;
	        		}
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:27,align:'center',sortable:false},
  	        {field:'partner_name',title:'合作方',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pnm = '<span style="color:red;">未设定</span>';
  	        		if(value && value.length>0) {
  	        			pnm = value;
  	        		}
	        		return pnm;
	        	}
		    },
  	        {field:'pay_platform',title:'支付平台',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var pf = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: pf="微信"; break;
  	        			case 20: pf="支付宝"; break;
  	        			case 30: pf="苹果内购"; break;
  	        		}
  	        		return pf;
	        	}
		    },
	        {field:'total_fee',title:'订单金额',width:35,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.order_id) return "N/A";
		    		  var show = Number(value||'0')/100;
		    		  return '<span style="color:red;">'+show+'</span>元';
		    	  }
		      },
		    {field:'express_type',title:'运费',width:20,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var mt = '<span style="color:red">未知</span>';
  	        		switch(Number(value||'0')){
  	        			case 10: mt='<span style="color:green">已付</span>'; break;
  	        			case 20: mt='<span style="color:red">到付</span>'; break;
  	        		}
  	        		return mt;
	        	}
		    },
//	        {field:'addr_name',title:'收件人',width:30,align:'center',sortable:false},
//		    {field:'addr_id',title:'收件地址',width:55,align:'left',sortable:false,
//  	        	formatter:function(value, rowData, rowIndex){
//  	        		if(!rowData.order_id) return "N/A";
//	        		return (rowData.addr_city||'') + ' '+ (rowData.addr_detail||'');
//	        	}
//		    },
	        {field:'create_time',title:'创建时间',width:80,align:'center',sortable:false},
	    ]],
	    hideColumn:['user_type'],
	    pagination : false,
		rownumbers : false
	});
}


// 查看将要导出用户文档订单
function initExOrderDocGrid(){
	var allOrderId = '';
	$('#exOrderDocGrid').datagrid({
		url:appPath + "/yjxOrders/getOrdersInfoPg.action?page=1&&rows=1000",
		striped:true,
		fitColumns:true,
		queryParams: getQueryParam(),
		singleSelect:false,
		fit:false,
		selectOnCheck:true,
		checkOnSelect:true,
		AllowPaging :false,
		columns:[[
		          {field:'order_id',title:'订单ID',width:25,align:'center',sortable:false,
		        	  formatter:function(value, rowData,rowIndex){
		        		  allOrderId += value +",";
		  	        	  $("#allOdrIds").val(allOrderId);
		        		  return value;
		        	  }
		          },
		          {field:'order_no',title:'订单号',width:50,align:'center',sortable:false},
		          {field:'pay_order_no',title:'支付订单号',width:50,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  return '<span style="color:red;">'+value+'</span>';
		        	  }
		          },
		          {field:'classify',title:'订单类型',width:53,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  var show = '<span style="color:#A020F0;">其它</span>';
		        		  switch (value){
		        		  case 1: show = '<span style="color:#3B3B3B;">[设计]去水印</span>';break;
		        		  case 1020: show = '<span style="color:#8B6914;">[视频]去水印</span>';break;
		        		  }
		        		  return show;
		        	  }
		          },
		          {field:'user_id',title:'用户ID',width:30,align:'center',sortable:false},
		          {field:'mobile',title:'用户手机',width:45,align:'center',sortable:false},
		          {field:'state',title:'状态',width:35,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  if(!rowData.order_id) return '<span style="color:red;">N/A</span>';
		        		  var show = getState4Show(value);
		        		  if(value==40||value==50) {
		        			  return show;
		        		  } else {
		        			  return show;
		        		  }
		        	  }
		          },
		          {field:'partner_name',title:'合作方',width:40,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  var pnm = '<span style="color:red;">未设定</span>';
		        		  if(value && value.length>0) {
		        			  pnm = value;
		        		  }
		        		  return pnm;
		        	  }
		          },
		          {field:'pay_platform',title:'支付平台',width:30,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  var pf = '<span style="color:red">未知</span>';
		        		  switch(Number(value||'0')){
		        		  case 10: pf="微信"; break;
		        		  case 20: pf="支付宝"; break;
		        		  case 30: pf="苹果内购"; break;
		        		  }
		        		  return pf;
		        	  }
		          },
		          {field:'total_fee',title:'订单金额',width:35,align:'center',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  if(!rowData.order_id) return "N/A";
		        		  var show = Number(value||'0')/100;
		        		  return '<span style="color:red;">'+show+'</span>元';
		        	  }
		          },
		          {field:'express_type',title:'运费',width:20,align:'left',sortable:false,
		        	  formatter:function(value, rowData, rowIndex){
		        		  var mt = '<span style="color:red">未知</span>';
		        		  switch(Number(value||'0')){
		        		  case 10: mt='<span style="color:green">已付</span>'; break;
		        		  case 20: mt='<span style="color:red">到付</span>'; break;
		        		  }
		        		  return mt;
		        	  }
		          },
		          {field:'create_time',title:'创建时间',width:80,align:'center',sortable:false},
		          ]],
		          hideColumn:['user_type'],
		          pagination : false,
		          rownumbers : false
	});
}

/**	重置时间
 * */
function clearTime(){
	$("#queryDateStart").datetimebox('setValue','');
	$("#queryDateEnd").datetimebox('setValue','');
}

//	 初始化加载 订单子订单详情
function initDetailGrid(){
	$('#detailGrid').datagrid({
	    url:appPath + "/yjxOrders/getDetailsInfoPg.action",
	    height:'300',
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'detail_id',title:'明细ID',width:30,align:'left',sortable:false},
	        {field:'detail_no',title:'明细编号',width:40,align:'left',sortable:false},
	        {field:'design_id',title:'模板ID',width:30,align:'left',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if (value){
	        			return value;
	        		}
	        		return 'N/A';
	        	}
	        },
	        {field:'type',title:'类型',width:30,align:'left',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		var ret = '';
	        		switch(value || '0'){
		        		case 10: ret = '<span style="color:green;">积分套餐</span>';break;
		        		case 20: ret = '<span style="color:#4876FF;">去水印</span>';break;
		        		case 30: ret = '<span style="color:#4876FF;">VIP套餐</span>';break;
	        		}
	        		return ret;
	        	}
	        },
	        {field:'qty',title:'数量',width:35,align:'left',sortable:false },
	        {field:'unit',title:'计量单位',width:30,align:'left',sortable:false },
	        {field:'fee',title:'金额值',width:35,align:'left',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if (value){
	        			return '<font color="">'+(value)/100+'元</font>';
	        		}
	        		return "0元";
	        	}
	        },
	        {field:'cost_pts',title:'消耗积分额',width:35,align:'center',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if (value){
	        			return '<font color="#6495ED">-'+(value)/100+'秀米</font>';
	        		}
	        		return 0;
	        	}
	        },
	        {field:'add_pts',title:'增加积分额',width:35,align:'center',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if (value){
	        			return '<font color="red">+'+(value)/100+'秀米</font>';
	        		}
	        		return 0;
	        	}
	        },
	        {field:'uni_doc_id',title:'用户作品',width:45,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = value;
	        		if (Number(value||'0')>0) {
	        			 if (rowData.topeType == 1){ // 判断是 模板水印 还是 视频去水印
	        				 var st = value +","+rowData.user_id;
	        				 var en = encrypt(st);
	        				 var url = getYjxHomeServer()+"/yjx/v1_0_0/outside/share?v="+en;
	        				 show = '<a href="' + url + '" target="_blank">模板作品:'+value+'</a>';
	        			 } else {
	        				 var thum = JSON.parse(rowData.vthumb);
	        				 show = '<a href="javascript:void(0)" onclick="playVideo(\''+thum[0]+'\',\''+rowData.url+'\')">视频作品:'+value+'</a>';
	        			 }
	        		} else {
	        			show = "N/A";
	        		}
	        		return show;
	        	}
	        },
	        {field:'create_time',title:'创建时间',width:60,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:60,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	    
	});
}

// 一键秀  接口加密
function encrypt(strIn){
	var strOut = '';
    if(strIn && strIn.length>0) {
        var arr = strIn.split(',');
        if(arr && arr.length<=5) {
            var arrSEP = [
                {R:26,S:'v'},
                {R:27,S:'w'},
                {R:28,S:'x'},
                {R:29,S:'y'},
                {R:30,S:'z'}
            ];
            for(var i=0; i<arr.length; i++) {
                var SEP = arrSEP[i];

                if(arr[i] && arr[i].length>0) {
                    var num = Number(arr[i]);
                    strOut += num.toString(SEP.R);
                }
                strOut += SEP.S;
            }
        }
    }
    return strOut;
}


//	播放视频资源
function playVideo(thumb,videoUrl){
	$('#playVideoDlg').window({
		title:'视频播放',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	if (!videoUrl){
		return $.messager.alert('警告','该视频资源暂无..','warning');
	}
	
	$('#playVideoDlg').window('move',{top:20,left:200});
	$('#playVideoDlg').window('open');
	var retUrl = '<a href="'+thumb+'" target ="_blank" '
	+ '<div style="display:table;text-align:center;height:150px;width:100%">'
	+ '<span style="display:table-cell;vertical-align:middle">'
	+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_146,w_250'
	+ '" style="display:inline;max-height:150px;max-width:400px"></span></div></a>';
	
	$("#videoThumb").html(retUrl);
	var htm = '<video style="margin-left:20px;height:270px;" controls="controls" preload="auto" poster="'+thumb+'" src="'+videoUrl+'"></video>';
	$("#viderUrl").html(htm);
}

function editUserDoc(id){
	$.messager.confirm('确定','是否确认修改用户作品？',function(r){
		if(r) {
			var editorUrl = getHomeServer()+"/encrypt/encrypt"+
			urlWithPara(
				{'isDesign':'0',// 字符类型
					'docId':id,
					'typeL':4,
					'isVip':'0',// 字符类型
					'destination':'/web_v6_0_goods/webV6_0/edit.html'
				});
			window.open(editorUrl);
		}
	});
}

function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:blue">待支付</span>'; break;
		case 11: state='<span style="color:green">已支付</span>'; break;
		case 12: state='<span style="color:red">付失败</span>'; break;
		case 20: state='<span style="color:brown">制作中</span>'; break;
		case 30: state='<span style="color:brown">配送中</span>'; break;
		case 40: state='<span style="color:green">完成</span>'; break;
		case 50: state='<span style="color:red">取消</span>'; break;
	}
	return state;
}

// 状态编辑
function editState(orderId,detailId){
	$("#stateDlg").show();
	$('#stateForm').form('clear');
	$("#updDesc").val('');
	$("#updOrderNo").html('');
	$("#updOrderState").combobox('enable');

	$("#updOrderId").val(orderId);
	$("#updDetailId").val(detailId);
	var url = appPath + "/yjxOrders/getOrdersInfoLst.action?order_id="+ orderId;
	
	/*if(Number(detailId||'0')>0){
		title = '订单明细(子订单)状态';
		url = appPath + "/yjxOrders/getDetailsInfoLst.action?detail_id="+ detailId;
	}*/
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updOrderNo").html(info.order_no||info.detail_no||'');
			$("#updOrderState").combobox('select',info.state||0);
			if(info.state==40) {
				$("#updOrderState").combobox('disable');// 已完成的不能改
			}
			$("#updDesc").val(info.desc||'');
			$("#updRecdInfo").val(JSON.stringify(info||{}));
		}
	});
	
	$("#stateBtn").show();
	$('#stateDlg').window({
		title: '订单状态',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#stateDlg').window('move',{top:20,left:20});
	$('#stateDlg').window('open');
}
function cancelUpdState(){
	$('#stateDlg').window('close');
}
function doUpdState(){// 更新
	var id = $("#updOrderId").val();
	var did = $("#updDetailId").val();
	var state = Number($("#updOrderState").combobox('getValue')||'0');
	var desc = $("#updDesc").val();
	var recdInfo = JSON.parse($("#updRecdInfo").val()||'{}');
	
	// 默认更新订单
	var url = appPath+"/yjxOrdersWeb/updOrder.action";
	var sendData = {
		"orderInfo.order_id": Number(id||"0"),
		"orderInfo.state": state,
		"orderInfo.desc": desc||''
	};
	
	/*	if(Number(did||'0')>0){
		// 更新订单明细
		url = appPath+"/yjxOrdersWeb/updDetail.action";
		sendData = {
			"detailInfo.detail_id": Number(did||"0"),
			"detailInfo.state": state,
			"detailInfo.desc": desc||''
		};
	} */
	
	$.loading(true);
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			// 添加历史纪录
			var url2 = appPath+"/yjxOrdersWeb/addStateHis.action";
			var sendData2 = {
				"stateHisInfo.type": 10,
				"stateHisInfo.trade_obj_id": Number(did||id||"0"),
				"stateHisInfo.total_fee": recdInfo.fee||recdInfo.total_fee||0,
				"stateHisInfo.user_id": recdInfo.user_id||0,
				"stateHisInfo.state": Number(state || "0"),
				"stateHisInfo.desc": desc||''
			};
			$.post(url2, sendData2, function(data2){
				$.loading(false);
				if(data == "ok") {
					$.messager.alert('提示信息','订单状态更新成功','info');
					$('#stateDlg').window('close');
					
					if(Number(did||'0')>0){
						doQuery2();
					} else {
						doQuery();
					}	
				} else {
					$.messager.alert('提示信息','订单状态已更新<br>但[状态历史]添加失败','info');
				}
			});
			
			// 发送[发货]通知
			if(state==30) {
				var url3 = appPath+"/yjxOrdersWeb/notifyUser.action";
				var sendData3 = {
					"orderInfo.order_id": Number(id||"0"),
					"orderInfo.user_id": Number(recdInfo.user_id||'0'),
					"orderInfo.state": Number(state || "0")
				};
				$.post(url3, sendData3, function(data3){
					if(data == "ok") {
						$.messager.alert('提示信息','用户通知已发送','info');
					} else {
						$.messager.alert('提示信息','用户通知发送失败','info');
					}
				});
			}
					
        } else {
        	$.loading(false);
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

// 打开订单明细（子订单）窗口
function showDetail(orderId){
	$('#detailForm').form('clear');
	$("#dtlOrderNo").html('');
	$("#dtlOrderId").val(orderId);
	
	var url = appPath + "/yjxOrders/getOrdersInfoLst.action?order_id="+ orderId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#dtlOrderNo").html(info.order_no||'');
			$("#dtlUserId").html(info.user_id||'');
		}
	});
	
	initDetailGrid();// 初始化 加载 订单内容
	
	$("#detailBtn").show();
	$('#detailDlg').window({
		title:'订单明细',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#detailDlg').window('move',{top:20,left:20});
	$('#detailDlg').window('open');
}

function closeDetail(){
	$('#detailDlg').window('close');
}

// 删除订单
function delOrder(){
	var selectItem=$("#ordersGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择订单！','warning');
		return;
	}
	for(var i=0; i<selectItem.length; i++){
		var chk = Number(selectItem[i].state||'0');
		if(chk==20||chk==40||chk==50){
			$.messager.alert('提示信息','不能删除当前状态的订单！','warning');
			return;
		}
	}
	$.messager.confirm("确认", "是否确认[删除]所选订单？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.order_id + ",";
				});
				var url = appPath+"/yjxOrdersWeb/delOrder.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

// 导出订单中用户文档信息
function downOdrUserDocInfo(id){
	var orderId = '';
	if (id == 0){
		orderId = $("#allOdrIds").val();
		if (orderId == null){
			$.messager.alert('警告','暂无用户文档需要导出的!','warning');
			return;
		} else {
			orderId = orderId.slice(0, orderId.length-1);
		}
	} else {
		orderId = id;
	}
	
	$.messager.confirm('确定','是否确定导出选中订单中的用户文档数据？',function(r){
		if(r){
			$.loading(true);
			var downUrl = appPath+"/yjxOrdersWeb/downOdrUserDocInfo.action";
			$.post(downUrl,{"orderId":(orderId||0)},function(ret){
				$.loading(false);
				if(ret && ret.length>0) {
					$("#exOrder").window('close');
					$("#exOrderGrid").html('');
					var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
					var fNm = "ITB_ODR_USERDOC_INFO_"+strDate+".csv";
					var blob = new Blob([ret]);
					var aLink = $('#downA');
					aLink.html(fNm);
					aLink.attr("download", fNm);
					aLink.attr("href", URL.createObjectURL(blob));
					$("#downBtn").show();
					$('#downDlg').window({
						title:'用户文档信息下载',
						iconCls:'icon-save',
						modal: true,
						shadow: true,
						collapsible:false,
						minimizable:false,
						maximizable:false
					});
					$('#downDlg').window('move',{top:20,left:20});
					$('#downDlg').window('open');
					
				} else {
					$.messager.alert('提示信息','数据获取失败','info');
				}
			});
		}
	});
}

// 导出订单信息
// flg: 1高精度,0普通精度  
// cutBleed: 0带出血,1不带出血 
//function downOrderInfo(orderId,flg,cutBleed){
//	var ret = '<span style="color:red;">未知</span>';
//	if (cutBleed == 0 && flg == 0){
//		ret = '<span style="color:blue;">普通精度</span><span style="color:red;">(带出血)</span>';
//	} else if(cutBleed == 0 && flg == 1 ) {
//		ret = '<span style="color:blue;">高精度</span><span style="color:red;">(带出血)</span>';
//	} else if(cutBleed == 1 && flg == 0){
//		ret = '<span style="color:blue;">普通精度</span><span style="color:green;">(不带出血)</span>';
//	} else if(cutBleed == 1 && flg == 1){
//		ret = '<span style="color:blue;">高精度</span><span style="color:green;">(不带出血)</span>';
//	} else {
//		return $.messager.alert('提示信息','参数设置错误！','info');
//	}
//	$.messager.confirm('确定','是否确定导出 '+ret+' 订单？',function(r){
//		if(r){
//			var ids='';
//			if(orderId==0){
//				ids = $("#allIds").val();
//				if(ids.length>0){
//					ids =ids.substr(0,ids.length-1);//去掉 最后一个逗号
//				}
//			}else{
//				ids=orderId;
//			}
//			if(ids){
//				$.loading(true);
//			//	var imgUrl = getApiServer()+"/print/createImageForPrint";
//				var imgUrl = getApiServer()+"/print/createImageForPrintEx";//一键导出 多个订单
//				var param = {
//					"device":1,
//					"reuse":0,/*重新生成*/
//					"orderId":(ids||0),
//					"cutBleed":Number(cutBleed,'0')
//				}
//				if(flg==1) {//获取高精度的图片
//					param.zoom=2;
//				} else {
//					param.zoom=1;
//				}
//				$.post(imgUrl, param, function(ret){
//					if(ret.success==1) {
//			//			var imgLst = ret.data.list||[];
//						var imgLst = ret.data||[];
//						if(imgLst.length>0){ 
//							var downUrl = appPath+"/yjxOrdersWeb/downOrderInfo.action";
//							$.post(downUrl,{"orderId":(ids||0),"printImgsInfo":JSON.stringify(imgLst),"withBleed":1,"zoom":param.zoom},function(ret){
//								$.loading(false);
//								if(ret && ret.length>0) {
//									$("#exOrder").window('close');
//									$("#exOrderGrid").html('');
//									var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
//									var fNm = "ITB_ORDER_INFO_"+strDate+".csv";
//									var blob = new Blob([ret]);
//									var aLink = $('#downA');
//									aLink.html(fNm);
//									aLink.attr("download", fNm);
//									aLink.attr("href", URL.createObjectURL(blob));
//									$("#downBtn").show();
//									$('#downDlg').window({
//										title:'订单信息下载',
//										iconCls:'icon-save',
//										modal: true,
//										shadow: true,
//										collapsible:false,
//										minimizable:false,
//										maximizable:false
//									});
//									$('#downDlg').window('move',{top:20,left:20});
//									$('#downDlg').window('open');
//									
//								} else {
//									$.messager.alert('提示信息','数据获取失败','info');
//								}
//							});
//								
//						}else{
//							$.loading(false);
//							$.messager.alert('提示信息','未获取到[印刷用图像文件]','info');
//						}
//					} else {
//						$.loading(false);
//						$.messager.alert('提示信息','生成[印刷用图像文件]失败','info');
//					}
//				});
//			}else{
//				$.messager.alert('提示信息','暂无订单可以导出！','info');
//			}
//		}
//	});
//}

// 导出 一键秀 订单信息
function downOrderInfo(orderId){
	$.messager.confirm('确定','是否确定导出订单?',function(r){
		if(r){
			var ids='';
			if(orderId==0){
				ids = $("#allIds").val();
				if(ids && ids.length>0){
					ids =ids.substr(0,ids.length-1);//去掉 最后一个逗号
				}
			}else{
				ids=orderId;
			}
			if(ids){
				$.loading(true);
				var downUrl = appPath+"/yjxOrdersWeb/downOrderInfo.action";
				$.post(downUrl,{"orderId":(ids||0)},function(ret){
								$.loading(false);
								if(ret && ret.length>0) {
									$("#exOrder").window('close');
									$("#exOrderGrid").html('');
									var strDate=$.DateUtil.format(new Date(),'yyyyMMddhhmmss');
									var fNm = "ITB_ORDER_INFO_"+strDate+".csv";
									var blob = new Blob([ret]);
									var aLink = $('#downA');
									aLink.html(fNm);
									aLink.attr("download", fNm);
									aLink.attr("href", URL.createObjectURL(blob));
									$("#downBtn").show();
									$('#downDlg').window({
										title:'导出订单信息',
										iconCls:'icon-save',
										modal: true,
										shadow: true,
										collapsible:false,
										minimizable:false,
										maximizable:false
									});
									$('#downDlg').window('move',{top:20,left:20});
									$('#downDlg').window('open');
									
								} else {
									$.messager.alert('提示信息','数据获取失败','info');
								}
						});				
			}else{
				$.messager.alert('提示信息','暂无订单可以导出！','info');
			}
		}
	});
}
function cancelDown(){
	$('#downDlg').window('close');
}

// 合作方
function editPartner(orderId,orderNo,pId) {
	$("#partnerDlg").show();
	$('#partnerForm').form('clear');

	$("#parOrderId").val(orderId);
	$("#parOrderNo").html(orderNo||'');
	$("#updPartner").combobox('select',pId||1);
	
	$("#partnerBtn").show();
	$('#partnerDlg').window({
		title: '合作方设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#partnerDlg').window('move',{top:20,left:20});
	$('#partnerDlg').window('open');
}
function cancelUpdPartner(){
	$('#partnerDlg').window('close');
}
function doUpdPartner(){
	var id = $("#parOrderId").val();
	var pId = $("#updPartner").combobox('getValue');
	
	var url = appPath+"/yjxOrdersWeb/updOrder.action";
	var sendData = {
		"orderInfo.order_id": Number(id||"0"),
		"orderInfo.partner_id": Number(pId || "0"),
	};
	
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			$.messager.alert('提示信息','更新成功','info');
			$('#partnerDlg').window('close');
			doQuery();
					
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}

/**
 * 获取请求信息(订单列表)
 */
function getQueryParam(){
	var queryObject = {};
	
	var findType = $("#queryType").combobox('getValue'); // 订单类型
	var findState = $("#queryState").combobox('getValue');// 订单状态
	var findPartner = $("#queryPartner").combobox('getValue');// 订单合伙人
	var findPay= $("#queryPayPf").combobox('getValue');// 订单支付状态
	var findOrderId = $("#queryOrderId").val();// 订单状态
	var findNo = $("#queryOrderNo").val();// 订单号
	var findPayNo = $("#queryPayOrderNo").val();// 支付订单号 
	var findInvId = $("#queryInvId").val();// 订单发票
	var findMobile = $("#queryMobile").val();// 用户手机号
	
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findUserId = $("#queryUserId").val();
	
	if (Number(findUserId)>0)queryObject.findUserId = findUserId;
	if(findType && findType.length>0) queryObject.findType = findType;// 分类
	if(findState && Number(findState||'0')>0) queryObject.findState = findState;// 状态
	if(findOrderId && Number(findOrderId||'0')>0) queryObject.findOrderId = findOrderId;// 订单id
	if(findNo && findNo.length>0) queryObject.findOrderNo = findNo;// 订单号
	if(findPayNo && findPayNo.length>0) queryObject.findPayOrderNo = findPayNo;// 支付订单号
	if(findPartner && Number(findPartner||'0')>0) queryObject.findPartner = findPartner;// 合作方
	if(findPay && Number(findPay||'0')>0) queryObject.findPayPf = findPay;// 支付平台
	if(findInvId && Number(findInvId||'0')>0) queryObject.findInvId = findInvId;// 发票id
	if(findMobile && Number(findMobile||'0')>0) queryObject.findMobile = findMobile;// 手机号

	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS+' 00:00:00';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59';
	
	return queryObject;
}


/**一键导出数据
 */
function exportAlls(){
	var par=$("#queryPartner").combobox('getValue');
	var startDate = $("#queryDateStart").datetimebox('getValue');
	var endDate = $("#queryDateEnd").datetimebox('getValue');
	if(startDate && startDate.length>0 && endDate && endDate.length>0){
		// 合作方(检索用)
		$("#exPartner").combobox({disabled:true});
		$("#exPartner").combobox({
			url:appPath+'/yjxOrders/getPartnerForCombo.action?blkFlg=1',
			valueField:'id',
			textField:'name',
			value:par
		});
		$("#exStartDate").val(startDate);
		$("#exStartDate").attr('readonly',true);
		$("#exEndDate").val(endDate);
		$("#exEndDate").attr('readonly',true);
		$("#exOrderBtn").show('slow');
		$('#exOrder').window({
			title: '订单物流信息',
			iconCls:'icon-edit',
			modal: true,
			shadow: false,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
		initExOrderGrid();
		$('#exOrder').window('move',{top:20,left:20});
		$('#exOrder').window('open');
	}else{
		$.messager.alert('提示信息','请选择需要导出的订单所在时间区间！','info');
	}
}

// 批量导出用户文档
function exportOdrDocInfo(){
	var startDate = $("#queryDateStart").datetimebox('getValue');
	var endDate = $("#queryDateEnd").datetimebox('getValue');
	if(startDate && startDate.length>0 && endDate && endDate.length>0){
		$("#exDocStartDate").val(startDate);
		$("#exDocStartDate").attr('readonly',true);
		$("#exDocEndDate").val(endDate);
		$("#exDocEndDate").attr('readonly',true);
		$("#exOrderDocBtn").show('slow');
		$('#exOrderDoc').window({
			title: '订单用户文档',
			iconCls:'icon-edit',
			modal: true,
			shadow: false,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});
		initExOrderDocGrid();
		$('#exOrderDoc').window('move',{top:20,left:20});
		$('#exOrderDoc').window('open');
	}else{
		$.messager.alert('提示信息','请选择订单所在时间区间','info');
	}
}


/**	取消	导出所有 订单
 **/
function cancleDown(){
	$("#exOrder").window('close');
	$("#exOrderGrid").html('');
}

function cancleDownDoc(){
	$("#exOrderDoc").window('close');
	$("#exOrderDocGrid").html('');
}

/** 查询数据
 */
function doQuery(){
	var findDtS = $("#queryDateStart").datebox('getValue');
	var findDtE = $("#queryDateEnd").datebox('getValue');
	if(findDtS && findDtS.length>0){
		var sDate=chkInputDate(findDtS);
		$("#queryDateStart").datetimebox('setValue',sDate);
	}
	if(findDtE && findDtE.length>0){
		var eDate=chkInputDate(findDtE);
		$("#queryDateEnd").datetimebox('setValue',eDate);
	}
	$("#ordersGrid").datagrid('unselectAll');
	$("#ordersGrid").datagrid(/*'load'*/'reload', getQueryParam());
}

function doQuery2(){
	$("#detailGrid").datagrid('unselectAll');
	$("#detailGrid").datagrid('load', getQueryParam2());
}
function getQueryParam2(){
	var queryObject = {
		findPubFlg: 1,
		findOrderId: Number($("#dtlOrderId").val()||'0')
	};
	return queryObject;
}

// 判断日期格式[YYYY-MM-DD]
function chkInputDate(str){
	var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;  
	var r = str.match(reg); 
	if(r==null)return '';  
	r[2]=r[2]-1;  
	var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);  
	if(d.getFullYear()!=r[1])return '';  
	if(d.getMonth()!=r[2])return '';  
	if(d.getDate()!=r[3])return '';  
	if(d.getHours()!=r[4])return '';  
	if(d.getMinutes()!=r[5])return '';  
	if(d.getSeconds()!=r[6])return '';  
	return str;  
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}
